<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>微信风格聊天室</title>
  <script src="/socket.io/socket.io.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
    }

    body {
      display: flex;
      height: 100vh;
      background-color: #f5f5f5;
    }

    .sidebar {
      width: 280px;
      background-color: #eee;
      border-right: 1px solid #ddd;
      display: flex;
      flex-direction: column;
    }

    .user-list {
      flex: 1;
      overflow-y: auto;
      padding: 10px;
    }

    .user-item {
      padding: 10px;
      margin-bottom: 5px;
      background-color: #fff;
      border-radius: 4px;
      cursor: pointer;
    }

    .chat-container {
      flex: 1;
      display: flex;
      flex-direction: column;
    }

    .chat-header {
      height: 60px;
      background-color: #eee;
      border-bottom: 1px solid #ddd;
      display: flex;
      align-items: center;
      padding: 0 20px;
      font-weight: bold;
    }

    .messages {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
      background-color: #f9f9f9;
    }

    .message {
      margin-bottom: 15px;
      display: flex;
      flex-direction: column;
      max-width: 70%;
    }

    .message-sender {
      font-size: 12px;
      color: #888;
      margin-bottom: 5px;
    }

    .message-content {
      padding: 10px 15px;
      border-radius: 4px;
      word-wrap: break-word;
    }

    .message.received {
      align-items: flex-start;
    }

    .message.received .message-content {
      background-color: #fff;
      border: 1px solid #ddd;
    }

    .message.sent {
      align-items: flex-end;
      margin-left: auto;
    }

    .message.sent .message-content {
      background-color: #95ec69;
    }

    .input-area {
      height: 120px;
      padding: 10px;
      background-color: #eee;
      border-top: 1px solid #ddd;
    }

    textarea {
      width: 100%;
      height: 80px;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      resize: none;
      outline: none;
    }

    .send-button {
      margin-top: 5px;
      padding: 8px 15px;
      background-color: #07c160;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      float: right;
    }

    .username-modal {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;
    }

    .username-box {
      background-color: white;
      padding: 20px;
      border-radius: 8px;
      width: 300px;
    }

    .username-box h2 {
      margin-bottom: 15px;
    }

    .username-box input {
      width: 100%;
      padding: 10px;
      margin-bottom: 15px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    .username-box button {
      padding: 8px 15px;
      background-color: #07c160;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    .error-message {
      color: red;
      font-size: 12px;
      margin-bottom: 10px;
    }

    /* 新增图片消息样式 */
    .message-image {
      max-width: 300px;
      max-height: 300px;
      border-radius: 4px;
      cursor: pointer;
      transition: transform 0.2s;
    }

    .message-image:hover {
      transform: scale(1.02);
    }

    .image-container {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.8);
      display: none;
      justify-content: center;
      align-items: center;
      z-index: 2000;
    }

    .image-container img {
      max-width: 90%;
      max-height: 90%;
    }

    .close-image {
      position: absolute;
      top: 20px;
      right: 20px;
      color: white;
      font-size: 30px;
      cursor: pointer;
    }

    .file-upload {
      display: none;
    }

    .upload-button {
      margin-right: 10px;
      padding: 8px 15px;
      background-color: #1989fa;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      float: left;
    }

    .message-time {
      font-size: 10px;
      color: #999;
      margin-top: 3px;
      text-align: right;
    }

    .message-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 3px;
    }
  </style>
</head>

<body>
  <div class="sidebar">
    <div class="chat-header">在线用户 (<span id="user-count">0</span>)</div>
    <div class="user-list" id="user-list"></div>
  </div>

  <div class="chat-container">
    <div class="chat-header">群聊</div>
    <div class="messages" id="messages"></div>
    <div class="input-area">
      <textarea id="message-input" placeholder="输入消息..."></textarea>
      <div style="overflow: hidden;">
        <button class="upload-button" id="upload-button">上传图片</button>
        <input type="file" id="file-upload" class="file-upload" accept="image/*">
        <button class="send-button" id="send-button">发送</button>
      </div>
    </div>
  </div>

  <div class="username-modal" id="username-modal">
    <div class="username-box">
      <h2>欢迎加入聊天室</h2>
      <p>请输入您的用户名</p>
      <div class="error-message" id="error-message"></div>
      <input type="text" id="username-input" placeholder="用户名">
      <button id="submit-username">确定</button>
    </div>
  </div>

  <div class="image-container" id="image-container">
    <span class="close-image" id="close-image">&times;</span>
    <img id="fullsize-image">
  </div>

  <script>
    const socket = io();
    let currentUser = '';

    // DOM元素
    const usernameModal = document.getElementById('username-modal');
    const usernameInput = document.getElementById('username-input');
    const submitUsername = document.getElementById('submit-username');
    const errorMessage = document.getElementById('error-message');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    const messagesContainer = document.getElementById('messages');
    const userList = document.getElementById('user-list');
    const userCount = document.getElementById('user-count');
    const uploadButton = document.getElementById('upload-button');
    const fileUpload = document.getElementById('file-upload');
    const imageContainer = document.getElementById('image-container');
    const fullsizeImage = document.getElementById('fullsize-image');
    const closeImage = document.getElementById('close-image');

    // 设置用户名
    submitUsername.addEventListener('click', () => {
      const username = usernameInput.value.trim();
      if (username) {
        socket.emit('set username', username, (response) => {
          if (response.success) {
            currentUser = username;
            usernameModal.style.display = 'none';
          } else {
            errorMessage.textContent = response.message;
          }
        });
      }
    });

    // 发送文本消息
    function sendMessage() {
      const message = messageInput.value.trim();
      if (message) {
        socket.emit('chat message', {
          message: message,
          isImage: false
        });
        messageInput.value = '';
      }
    }

    sendButton.addEventListener('click', sendMessage);
    messageInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
      }
    });

    // 上传图片处理
    uploadButton.addEventListener('click', () => {
      fileUpload.click();
    });

    fileUpload.addEventListener('change', async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      if (!file.type.match('image.*')) {
        alert('请选择图片文件');
        return;
      }

      if (file.size > 5 * 1024 * 1024) {
        alert('图片大小不能超过5MB');
        return;
      }

      const formData = new FormData();
      formData.append('image', file);

      try {
        uploadButton.disabled = true;
        uploadButton.textContent = '上传中...';

        const response = await fetch('/upload', {
          method: 'POST',
          body: formData
        });

        const result = await response.json();

        if (result.url) {
          socket.emit('chat message', {
            message: file.name,
            isImage: true,
            imageUrl: result.url
          });
        }
      } catch (error) {
        console.error('上传失败:', error);
        alert('图片上传失败');
      } finally {
        uploadButton.disabled = false;
        uploadButton.textContent = '上传图片';
        fileUpload.value = '';
      }
    });

    // 关闭图片预览
    closeImage.addEventListener('click', () => {
      imageContainer.style.display = 'none';
    });

    // 添加消息到界面
    function addMessage(user, message, isSent = false, isImage = false, imageUrl = null, timestamp = null) {
      const messageElement = document.createElement('div');
      messageElement.className = `message ${isSent ? 'sent' : 'received'}`;

      const senderElement = document.createElement('div');
      senderElement.className = 'message-sender';
      senderElement.textContent = user;

      const contentElement = document.createElement('div');
      contentElement.className = 'message-content';

      if (isImage && imageUrl) {
        const imgElement = document.createElement('img');
        imgElement.src = imageUrl;
        imgElement.className = 'message-image';
        imgElement.alt = message;
        imgElement.addEventListener('click', () => {
          fullsizeImage.src = imageUrl;
          imageContainer.style.display = 'flex';
        });
        contentElement.appendChild(imgElement);
      } else {
        contentElement.textContent = message;
      }

      const footerElement = document.createElement('div');
      footerElement.className = 'message-footer';

      const timeElement = document.createElement('div');
      timeElement.className = 'message-time';
      timeElement.textContent = timestamp || new Date().toLocaleTimeString();
      footerElement.appendChild(timeElement);

      messageElement.appendChild(senderElement);
      messageElement.appendChild(contentElement);
      messageElement.appendChild(footerElement);

      messagesContainer.appendChild(messageElement);
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // 更新用户列表
    function updateUserList(users) {
      userList.innerHTML = '';
      userCount.textContent = users.length;

      users.forEach(user => {
        const userElement = document.createElement('div');
        userElement.className = 'user-item';
        userElement.textContent = user;
        userList.appendChild(userElement);
      });
    }

    // Socket.io事件监听
    socket.on('chat message', (data) => {
      addMessage(
        data.user,
        data.message,
        data.isCurrentUser,
        data.isImage,
        data.imageUrl,
        data.timestamp
      );
    });

    socket.on('welcome', (message) => {
      addMessage('系统', message);
    });

    socket.on('user joined', (username) => {
      addMessage('系统', `${username} 加入了聊天室`);
    });

    socket.on('user left', (username) => {
      addMessage('系统', `${username} 离开了聊天室`);
    });

    socket.on('update users', (users) => {
      updateUserList(users);
    });
  </script>
</body>

</html>